﻿using ESRI.ArcGIS.Geodatabase;
using Inovout.Gis;
using Inovout.Gis.Geometry;
using ESRI.ArcGIS.esriSystem;
using ESRI.ArcGIS.Carto;
using System.Collections.Generic;
using ESRI.ArcGIS.Geometry;

namespace Inovout.ArcGis
{
    public class ArcGisInfoRepository : ArcGisRepository, IGisInfoRepository
    {
        internal ArcGisInfoRepository(IWorkspace worksapce)
            : base(worksapce)
        {
        }
        public ArcGisInfoRepository(IPropertySet datasourceConfig)
            : base(datasourceConfig)
        {
        }

        public IGeometryLayerInfo GetGeometryLayer(string layerName)
        {
            IFeatureClass featureClass = base.GetFeatureClass(layerName);
            IFeatureLayer featureLayer = new FeatureLayerClass();
            featureLayer.FeatureClass = featureClass;
            return ArcGisHelper.CreateLayer(null, featureLayer) as IGeometryLayerInfo;
        }

        public IGeometryInfo GetGeometry(string layerName, object geometryId)
        {
            IGisTable gisTable = base.GetTable(layerName);
            IGisRow gisRow = gisTable.GetRow(geometryId);
            return gisRow.BuildGeometryInfo();
        }

        internal List<IGeometryInfo> FindIntersectedGeometriesByEnvelope(string layerName, IGeometry geometry)
        {
            IQueryFilter queryFilter = new QueryFilterClass();
            string whereString = string.Format(
             @"(GeometryInfo.EnvelopeMinXFieldName < {0} and GeometryInfo.EnvelopeMaxYFieldName > {3}) or
                   (GeometryInfo.EnvelopeMaxXFieldName > {1} and GeometryInfo.EnvelopeMaxYFieldName > {3}) or
                   (GeometryInfo.EnvelopeMinXFieldName < {0} and GeometryInfo.EnvelopeMinXFieldName < {2}) or
                   (GeometryInfo.EnvelopeMaxXFieldName > {1} and GeometryInfo.EnvelopeMinXFieldName < {2})",
               geometry.Envelope.XMin,
               geometry.Envelope.XMax,
               geometry.Envelope.YMin,
               geometry.Envelope.YMax);

            queryFilter.WhereClause = whereString;
            IFeatureClass featureClass = GetFeatureClass(layerName);
            IFeatureCursor featureCursor = featureClass.Search(queryFilter, false);
            List<IGeometryInfo> geometries = new List<IGeometryInfo>();
            IFeature feature = featureCursor.NextFeature();

            while (feature != null)
            {
                geometries.Add(ArcGisHelper.CreateArcGeometry(feature.Shape));
            }
            return geometries;
        }
    }
}
